#!/bin/bash

if [[ -z "$CONFIG_FILE" ]]; then
	FILENAME="/opt/selenium/config.toml"
else
	FILENAME="$CONFIG_FILE"
fi

if [[ -n "${SE_NODE_RELAY_URL}" ]]; then
	echo "[relay]" >>"$FILENAME"
	echo "url = \"$(envsubst < <(echo ${SE_NODE_RELAY_URL}))\"" >>"$FILENAME"
	if [[ -z "${SE_NODE_RELAY_STATUS_ENDPOINT}" ]]; then
		echo "status-endpoint = \"/status\"" >>"$FILENAME"
	else
		echo "status-endpoint = \"${SE_NODE_RELAY_STATUS_ENDPOINT}\"" >>"$FILENAME"
	fi
	if [[ -n "${SE_NODE_RELAY_PROTOCOL_VERSION}" ]]; then
		echo "protocol-version = \"${SE_NODE_RELAY_PROTOCOL_VERSION}\"" >>"$FILENAME"
	fi
	if [[ -z "${SE_NODE_RELAY_STEREOTYPE}" ]]; then
		SE_NODE_RELAY_STEREOTYPE="{\"browserName\": \"${SE_NODE_RELAY_BROWSER_NAME:-${SE_NODE_BROWSER_NAME}}\", \"platformName\": \"${SE_NODE_RELAY_PLATFORM_NAME:-${SE_NODE_PLATFORM_NAME}}\"}"
		if [[ -n "${SE_NODE_RELAY_PLATFORM_VERSION}" ]]; then
			SE_NODE_RELAY_STEREOTYPE="$(python3 /opt/bin/json_merge.py "${SE_NODE_RELAY_STEREOTYPE}" "{\"appium:platformVersion\":\"${SE_NODE_RELAY_PLATFORM_VERSION}\"}")"
		fi
		BROWSER_VERSION=${SE_NODE_RELAY_BROWSER_VERSION:-${SE_NODE_BROWSER_VERSION}}
		if [[ -n "${BROWSER_VERSION}" ]] && [[ "${BROWSER_VERSION}" != "stable" ]]; then
			SE_NODE_RELAY_STEREOTYPE="$(python3 /opt/bin/json_merge.py "${SE_NODE_RELAY_STEREOTYPE}" "{\"browserVersion\":\"${BROWSER_VERSION}\"}")"
		fi
		if [[ "${SE_NODE_ENABLE_MANAGED_DOWNLOADS}" = "true" ]]; then
			SE_NODE_RELAY_STEREOTYPE="$(python3 /opt/bin/json_merge.py "${SE_NODE_RELAY_STEREOTYPE}" "{\"se:downloadsEnabled\": true}")"
		fi
	else
		SE_NODE_RELAY_STEREOTYPE="${SE_NODE_RELAY_STEREOTYPE}"
	fi
	if [[ -n "${SE_NODE_RELAY_STEREOTYPE_EXTRA}" ]]; then
		echo "Merging SE_NODE_RELAY_STEREOTYPE_EXTRA=${SE_NODE_RELAY_STEREOTYPE_EXTRA} to main relay stereotype"
		SE_NODE_RELAY_STEREOTYPE="$(python3 /opt/bin/json_merge.py "${SE_NODE_RELAY_STEREOTYPE}" "${SE_NODE_RELAY_STEREOTYPE_EXTRA}")"
		if [[ $? -ne 0 ]]; then
			echo "Failed to merge SE_NODE_RELAY_STEREOTYPE_EXTRA. Please check the format of the JSON string. Keep using main relay stereotype."
		else
			echo "Merged relay stereotype: ${SE_NODE_RELAY_STEREOTYPE}"
		fi
	fi
	echo "configs = ['${SE_NODE_MAX_SESSIONS:-${SE_NODE_RELAY_MAX_SESSIONS}}', '${SE_NODE_RELAY_STEREOTYPE}']" >>"$FILENAME"
fi
